/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="condition" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="condition.status" placeholder="请选择">
          <el-option label="转态" value=""></el-option>
          <el-option label="正常" value="01"></el-option>
          <el-option label="已锁定" value="00"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select size="small" v-model="condition.sex" placeholder="性别">
          <el-option label="性别" value=""></el-option>
          <el-option label="男" value="01"></el-option>
          <el-option label="女" value="00"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="condition.userName"
          placeholder="输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="condition.phone"
          placeholder="输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit('add')"
          >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!--列表-->
    <div>
      <el-button
        size="mini"
        type="danger"
        @click="delUsers"
        style="margin-bottom: 5px"
        >批量删除</el-button
      >
    </div>
    <el-table
      size="small"
      @selection-change="selectChange"
      :data="userData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>

      <el-table-column align="center" type="index" label="NO." width="50">
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="userName"
        label="用户名"
        width="120"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="realName"
        label="姓名"
        width="120"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="phone"
        label="手机号"
        width="120"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="sex"
        label="性别"
        min-width="50"
        :formatter="sexFormat"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="email"
        label="邮件"
        min-width="100"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="updateTime"
        label="修改时间"
        min-width="100"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="isLock"
        label="状态"
        min-width="50"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="01"
            inactive-value="00"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="setStatus(scope.row.id, scope.row.status)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit('edit', scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="deleteUser(scope.row.id)"
            >删除</el-button
          >
          <el-button size="mini" type="success" @click="resetpwd(scope.row)"
            >重置密码</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="handleEdit('view', scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form
        label-width="80px"
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input
                size="small"
                v-model="editForm.userName"
                auto-complete="off"
                placeholder="请输入用户名"
                :disabled="!showPWD"
              ></el-input>
            </el-form-item>

            <el-form-item v-if="showPWD" label="密码" prop="password">
              <el-input
                size="small"
                type="password"
                v-model="editForm.password"
                auto-complete="off"
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>

            <el-form-item v-if="showPWD" label="再次输入" prop="password1">
              <el-input
                size="small"
                type="password"
                v-model="editForm.password1"
                auto-complete="off"
                placeholder="请再次输入密码"
              ></el-input>
            </el-form-item>

            <el-form-item label="昵称" prop="nickName">
              <el-input
                size="small"
                v-model="editForm.nickName"
                auto-complete="off"
                placeholder="请输入昵称"
                :disabled="isView"
              ></el-input>
            </el-form-item>

            <el-form-item label="姓名" prop="realName">
              <el-input
                size="small"
                v-model="editForm.realName"
                auto-complete="off"
                placeholder="请输入姓名"
                :disabled="isView"
              ></el-input>
            </el-form-item>

            <el-form-item label="角色" prop="roles">
              <el-checkbox-group
                size="small"
                v-model="editForm.roles"
                placeholder="请选择"
                class="userRole"
                :disabled="isView"
              >
                <el-checkbox
                  v-for="(a, index) in roles"
                  :key="index"
                  :label="a.id"
                  >{{ a.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input
                size="small"
                v-model="editForm.phone"
                placeholder="请输入手机号"
                :disabled="isView"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮件" prop="email">
              <el-input
                size="small"
                v-model="editForm.email"
                placeholder="请输入邮箱地址"
                :disabled="isView"
              ></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio v-model="editForm.sex" label="01" :disabled="isView"
                >男</el-radio
              >
              <el-radio v-model="editForm.sex" label="00" :disabled="isView"
                >女</el-radio
              >
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item>
              <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:8090/user/icon"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :disabled="isView"
              >
                <img
                  v-if="editForm.iconUrl"
                  :src="editForm.iconUrl"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          v-if="!isView"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
export default {
  inject: ["reload"],
  data() {
    //校验再一次输入密码
    var validatePass1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.editForm.password != this.editForm.password1) {
          callback(new Error("密码不一致!"));
        } else {
          callback();
        }
      }
    };

    //校验用户名
    var validateUserName = async (rule, value, callback) => {
      let c = {
        id: this.editForm.id,
        userName: value,
      };
      var d = await this.$axios.post("/user/checkByUName", c);
      if (d.code == 200) {
        if (d.message == "0") {
          callback();
        } else {
          callback("用户名已存在");
        }
      }
    };
    return {
      loading: false, //是显示加载
      showPWD: false,
      isView: false,
      title: "添加用户",
      editFormVisible: false, //控制编辑页面显示与隐藏

      // 编辑与添加
      editForm: {
        id: "",
        userName: "",
        nickName: "",
        realName: "",
        iconUrl: "",
        roles: [],
        phone: "",
        email: "",
        sex: "",
        password: "",
        password1: "",
      },
      //角色
      roles: [],
      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: validateUserName, trigger: "blur" },
        ],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]{6,20}$/,
            required: true,
            message: "密码只包含大小写字母或数字,且长度为6-20",
            trigger: "blur",
          },
        ],
        password1: [
          { validator: validatePass1, required: true, trigger: "blur" },
        ],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        // roles: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            required: true,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            required: true,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
      },

      // 请求数据参数
      condition: {
        currentPage: 1,
        pageSize: 10,
        userName: "",
        phone: "",
        sex: "",
        status: "",
      },
      //用户数据
      userData: [],

      // 选中
      checkmenu: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  // 注册组件
  components: {
    Pagination,
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {
    this.init();
    this.getAllRoles();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //初始化表格
    async init() {
      this.loading = true;
      var d = await this.$axios.post("/user/page", this.condition);
      if (d.code == 200) {
        this.userData = d.data.records;
        this.pageparm.currentPage = d.data.current;
        this.pageparm.pageSize = d.data.size;
        this.pageparm.total = d.data.total;
      }
      this.loading = false;
    },

    //获取角色
    async getAllRoles() {
      var d = await this.$axios.get("/role/all");
      this.roles = d.data;
    },

    //初始化角色
    initRoles(roles) {
      let r = [];
      for (let i = 0; i < roles.length; i++) {
        r.push(this.roles[i].id);
      }
      this.editForm.roles = r;
    },

    //性别格式化
    sexFormat(row, column, cellValue, index) {
      return cellValue == "01" ? "男" : "女";
    },

    // 分页插件事件
    callFather(parm) {
      this.condition.currentPage = parm.currentPage;
      this.condition.pageSize = parm.pageSize;
      this.init(this.condition);
    },

    //搜索事件
    search() {
      this.init();
    },

    //修改用户状态
    async setStatus(id, status) {
      this.loading = true;
      let param = {
        id: id,
        status: status,
      };
      var d = await this.$axios.put("/user/status", param);
      if (d.code == 200) {
        this.$message.success(d.message);
      } else {
        this.$message.error(d.message);
      }
      this.loading = false;
    },

    //显示编辑界面
    handleEdit: function (name, row) {
      this.editFormVisible = true;
      if (name == "edit" || name == "view") {
        this.showPWD = false;
        this.isView = name == "view" ? true : false;
        this.title = "修改用户";
        this.editForm.id = row.id;
        this.editForm.userName = row.userName;
        this.editForm.iconUrl = row.iconUrl;
        this.editForm.nickName = row.nickName;
        this.editForm.realName = row.realName;
        this.editForm.phone = row.phone;
        this.editForm.email = row.email;
        this.editForm.sex = row.sex;
        this.initRoles(row.roles);
      } else {
        this.showPWD = true;
        this.isView = false;
        this.title = "添加用户";
        this.editForm.iconUrl = "";
      }
    },

    // 编辑、添加提交方法
    submitForm(editData) {
      this.$refs[editData].validate(async (valid) => {
        if (valid) {
          if (this.showPWD) {
            //为true是表示添加
            var d = await this.$axios.post("/user/add", this.editForm);
            if (d.code == 200) {
              this.$message.success(d.message);
              this.editFormVisible = false;
              this.$refs.editForm.resetFields();
            } else {
              this.$message.error(d.message);
            }
          } else {
            //为false是表示修改
            var d = await this.$axios.put("/user/update", this.editForm);
            if (d.code == 200) {
              this.$message.success(d.message);
              this.editFormVisible = false;
            } else {
              this.$message.error(d.message);
            }
          }
          this.reload();
        } else {
          this.$message.warning("填写有误,请重新填写!");
        }
      });
    },

    //图片上传成功时
    handleAvatarSuccess(res, file) {
      this.editForm.iconUrl = res.message;
    },
    //图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val;
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
      this.$refs.editForm.resetFields();
    },

    // 删除用户
    deleteUser(id) {
      this.loading = true;
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          var d = await this.$axios.delete("/user/del/" + id);
          if (d.code == 200) {
            this.loading = false;
            this.$message.success(d.message);
            this.reload();
          } else {
            this.loading = false;
            this.$message.error(d.message);
          }
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "info",
            message: "已取消删除！",
          });
        });
    },

    //批量删除用户
    delUsers() {
      if (this.selectdata.length <= 0) {
        return;
      }
      this.loading = true;
      let ids = [];
      for (let i = 0; i < this.selectdata.length; i++) {
        ids.push(this.selectdata[i].id);
      }
      this.$confirm("确定要删除选中的用户吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          var d = await this.$axios.post("/user/dels", ids);
          if (d.code == 200) {
            this.loading = false;
            this.$message.success(d.message);
            this.reload();
          } else {
            this.loading = false;
            this.$message.error(d.message);
          }
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "info",
            message: "已取消删除！",
          });
        });
    },
    // 重置密码
    resetpwd(row) {
      this.loading = true;
      this.$confirm("确定要重置密码为: 123456 吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let c = {
            id: row.id,
            userName: row.userName,
            password: "123456",
          };
          var d = await this.$axios.post("/user/resetPWD", c);
          if (d.code == 200) {
            this.loading = false;
            this.$message.success(d.message);
          } else {
            this.loading = false;
            this.$message.error(d.message);
          }
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "info",
            message: "取消重置密码！",
          });
        });
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

 